package net.modul.customer.dao.impl;

import java.util.List;

import net.common.dao.GeneralDaoImpl;
import net.common.db.ConnectionManager;
import net.common.service.PageBean;
import net.modul.customer.dao.CustomerDao;
import net.modul.customer.vo.CustomerVo;

import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

public class CustomerDaoImpl extends GeneralDaoImpl implements CustomerDao {

	@Override
	public List<CustomerVo> search(PageBean pageBean, CustomerVo bean)
			throws Exception {
		String sql = "select cust_id,cust_num,cust_name,jane_spell,industry,linkman,phone,telphone,address,email,statu,flag from t_customer where flag=0";
		if(bean != null) {			
			if (bean.getCust_num() != null && !bean.getCust_num().equals("")) {
				sql += " and cust_name=?";
			}
			if (bean.getCust_name() != null) {
				sql += " and cust_name like '%?%'";
			}
		}
		ResultSetHandler<List<CustomerVo>> rsh = new BeanListHandler<CustomerVo>(
				CustomerVo.class);
		return gqr.querySplitPage(sql, rsh, bean, pageBean, null);
	}

	@Override
	public void insert(CustomerVo bean) throws Exception {
		String sql = "insert into t_customer (cust_num,cust_name,jane_spell,industry,linkman,phone,telphone,address,email,statu,flag) values (?,?,?,?,?,?,?,?,?,?,?)";
		gqr.insert(sql, bean);
	}

	@Override
	public void update(CustomerVo bean) throws Exception {
		String sql = "update t_customer set cust_name=?,jane_spell=?,industry=?,linkman=?,phone=?,telphone=?,address=?,email=? where cust_id=?";
		gqr.updateByBean(sql, bean);
	}

	@Override
	public void updateFlag(CustomerVo bean) throws Exception {
		String sql = "update t_customer set flag=? where cust_id=?";
		gqr.updateByBean(sql, bean);
	}

	@Override
	public CustomerVo find(Integer id) throws Exception {
		String sql = "select cust_id,cust_num,cust_name,jane_spell,industry,linkman,phone,telphone,address,email,statu,flag from t_customer where cust_id=?";
		ResultSetHandler<CustomerVo> rsh = new BeanHandler<CustomerVo>(
				CustomerVo.class);
		return gqr.query(ConnectionManager.getConnection(), sql, rsh, new Object[] { id });
	}

	@Override
	public String findText(Integer id) throws Exception {
		String sql = "select cust_type from t_customer where cust_id=?";
		return gqr.query(ConnectionManager.getConnection(), sql, new ScalarHandler<String>(), new Object[] { id });
	}

	@Override
	public void insertText(CustomerVo bean) throws Exception {
		String sql = "update t_customer set cust_type=? where cust_id=?";
		gqr.updateByBean(sql, bean);
	}
}
